package com.coalmine.api.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.coalmine.api.domain.ApiDatasource;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public class PoolManager {
    //所有数据源的连接池存在map里
    static ConcurrentHashMap<String, DruidDataSource> map = new ConcurrentHashMap<>();

    public static DruidDataSource getJdbcConnectionPool(ApiDatasource ads) {
        if (map.containsKey(ads.getId())) {
            return map.get(ads.getId());
        } else {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setName(ads.getName());
            druidDataSource.setUrl(ads.getUrl());
            druidDataSource.setUsername(ads.getUsername());
            druidDataSource.setDriverClassName(ads.getDriver());
            druidDataSource.setConnectionErrorRetryAttempts(1); //失败后重连次数
            druidDataSource.setBreakAfterAcquireFailure(true);
            //连接池支持的最大连接数
            druidDataSource.setMaxActive(20);
            //连接池中最小空闲连接数
            druidDataSource.setMinIdle(5);
            druidDataSource.setInitialSize(10);
            druidDataSource.setTestWhileIdle(false);
            //活动连接的最大空闲时间
            //druidDataSource.setRemoveAbandonedTimeout(5);
            //超过“removeAbandonedTimout”设置的无效连接将会被清除
            //druidDataSource.setRemoveAbandoned(true);
            //最大等待时间毫秒
            druidDataSource.setMaxWait(3000);
            try {
                druidDataSource.setPassword(DESUtils.decrypt(ads.getPassword()));
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
            map.put(ads.getId(), druidDataSource);
            log.info("create druid datasource：{}", ads.getName());
            return map.get(ads.getId());

        }
    }

    //删除数据库连接池
    public static void removeJdbcConnectionPool(String id) {
        if (map.containsKey(id)) {
            DruidDataSource old = map.get(id);
            map.remove(id);
            old.close();
            log.info("remove druid datasource: {}", old.getName());
        }
    }

    public static DruidPooledConnection getPooledConnection(ApiDatasource ads) throws SQLException {
        DruidDataSource pool = PoolManager.getJdbcConnectionPool(ads);
        DruidPooledConnection connection = pool.getConnection();
//        log.info("获取连接成功");
        return connection;
    }
}
